package com.lfy.chat.handler;


import cn.hutool.json.JSONUtil;
import com.lfy.chat.domain.ws.req.ChatReq;
import com.lfy.chat.domain.ws.resp.BaseResp;
import com.lfy.chat.service.ChatService;
import com.lfy.chat.service.impl.ChatServiceImpl;
import com.lfy.chat.strategy.ChatStrategy;
import com.lfy.common.constant.GlobalConstant;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
/**
 * chat处理器
 *
 * @author <a href="https://www.lvfeiy.top">吕飞扬</a>
 * @date 2023/10/25 0:27
 */
@Slf4j
public class LfyImServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private ChatService chatService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接成功"+ctx.channel().id().asShortText());

    }

    /**
     *  当web客户端连接后，触发该方法（Channel成功绑定一个逻辑处理器）
     * @param ctx 上下文
     */

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//        chatService = SpringUtil.getBean("chatServiceImpl");
        chatService = new ChatServiceImpl();
    }

    /**
     * 断开连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("触发 channelInactive 掉线![{}]", ctx.channel().id());
        chatService.unBind(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

        ChatReq chatReq = JSONUtil.toBean(textWebSocketFrame.text(), ChatReq.class);
        log.info("收到{}消息，{}",channelHandlerContext.channel().id().asShortText(),chatReq);
        Channel channel = channelHandlerContext.channel();
        if(chatReq != null && chatReq.getType() != null){
            ChatStrategy.STRATEGY_MAP.get(chatReq.getType()).execute(channel,chatReq);
        }else {
            BaseResp<Void> resp = new BaseResp<>();
            resp.setType(GlobalConstant.STRING_0);
            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(resp)));
        }
    }

    /**
     * 出现异常时触发
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("ws: error :",cause);
        ctx.channel().close();
    }


}
